package org.ww.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ww.common.constant.ProductConstant;
import org.ww.common.utils.PageUtils;
import org.ww.common.utils.Query;
import org.ww.product.dao.AttrGroupDao;
import org.ww.product.entity.AttrAttrgroupRelationEntity;
import org.ww.product.entity.AttrEntity;
import org.ww.product.entity.AttrGroupEntity;
import org.ww.product.service.AttrAttrgroupRelationService;
import org.ww.product.service.AttrGroupService;
import org.ww.product.service.AttrService;
import org.ww.product.vo.AttrGroupRelationVo;
import org.ww.product.vo.AttrGroupWithAttrVo;
import org.ww.product.vo.SpuItemAttrGroupVo;

import java.util.*;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        LambdaQueryWrapper<AttrGroupEntity> wrapper = Wrappers.lambdaQuery();
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            wrapper.and(obj -> {
                obj.eq(AttrGroupEntity::getAttrGroupId,key)
                        .or()
                        .like(AttrGroupEntity::getAttrGroupName,key);
            });
        }

        if(catelogId == 0){
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        }

        wrapper.eq(AttrGroupEntity::getCatelogId,catelogId);
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);

    }


    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {

        List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = Arrays.stream(vos).map(item -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());

        baseMapper.deleteAttrGroupRelation(attrgroupRelationEntityList);

    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {

        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = baseMapper.selectById(attrgroupId);
        //获取当前分类的id
        Long catelogId = attrGroupEntity.getCatelogId();

        //2、当前分组只能关联别的分组没有引用的属性
        //2.1）、当前分类下的其它分组
        List<AttrGroupEntity> groupEntities = baseMapper.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));

        //获取到所有的attrGroupId
        List<Long> collect = groupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());


        //2.2）、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = attrAttrgroupRelationService.list
                (new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));

        List<Long> attrIds = groupId.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3）、从当前分类的所有属性移除这些属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrIds != null && attrIds.size() > 0) {
            queryWrapper.notIn("attr_id", attrIds);
        }

        //判断是否有参数进行模糊查询
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and((w) -> {
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = attrService.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    @Override
    public List<AttrGroupWithAttrVo> catelogWithattr(Long catelogId) {
        List<AttrGroupWithAttrVo> attrGroupWithAttrVos = new ArrayList<>();
        //查询属性分组
        LambdaQueryWrapper<AttrGroupEntity> attrGroupWrapper = Wrappers.lambdaQuery();
        attrGroupWrapper.eq(AttrGroupEntity::getCatelogId,catelogId);
        List<AttrGroupEntity> attrGroupEntities = baseMapper.selectList(attrGroupWrapper);

        //获取所有属性
        List<Long> attrGroupIds = Optional.ofNullable(attrGroupEntities)
                .orElseGet(ArrayList::new)
                .stream()
                .map(AttrGroupEntity::getAttrGroupId)
                .distinct()
                .collect(Collectors.toList());

        LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.in(AttrAttrgroupRelationEntity::getAttrGroupId,attrGroupIds);
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.list(wrapper);

        List<AttrEntity> attrEntityList = attrService.getByAttrGroupIds(attrGroupIds);

        if(CollectionUtils.isNotEmpty(attrGroupEntities)){
            for (AttrGroupEntity attrGroupEntity : attrGroupEntities) {
                AttrGroupWithAttrVo vo = new AttrGroupWithAttrVo();
                BeanUtils.copyProperties(attrGroupEntity,vo);

                List<Long> AttrIds = Optional.ofNullable(attrAttrgroupRelationEntities)
                        .orElseGet(ArrayList::new)
                        .stream()
                        .filter(a -> a.getAttrGroupId().equals(attrGroupEntity.getAttrGroupId()))
                        .map(AttrAttrgroupRelationEntity::getAttrId)
                        .distinct()
                        .collect(Collectors.toList());

                //过滤所有的属性列表
                List<AttrEntity> attrEntities = Optional.ofNullable(attrEntityList)
                        .orElseGet(ArrayList::new)
                        .stream()
                        .filter(a -> AttrIds.contains(a.getAttrId()))
                        .collect(Collectors.toList());

                vo.setAttrs(attrEntities);
                attrGroupWithAttrVos.add(vo);
            }

        }
        return attrGroupWithAttrVos;
    }

    @Override
    public List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId,Long catalogId) {
        //1 查出当前spu对应的所有属性的分组信息以及当前分组下的所有属性对应的值
        List<SpuItemAttrGroupVo> spuItemAttrGroupVos = baseMapper.getAttrGroupWithAttrsBySpuId(spuId,catalogId);
        return spuItemAttrGroupVos;
    }

}